import React, { useState, useEffect } from 'react';
import Header from './components/Header';
import Sidebar from './components/Sidebar';
import ContentArea from './components/ContentArea';
import AuthModal from './components/AuthModal';
import LoadingModal from './components/LoadingModal';

const API_BASE_URL = 'http://localhost:5656/api/v1'; // 后端API基础URL

interface Category {
    id: string;
    name: string;
    icon?: string;
    color?: string;
    channel_count: number;
    is_default: boolean;
    sort_order: number;
}

interface Channel {
    id: string;
    channel_id: string;
    title: string;
    thumbnail_url: string;
    subscriber_count: number;
    video_count: number;
    last_video_published_at: string;
    sync_status: string;
}

interface Video {
    title: string;
    channel: string;
    duration: string;
    views: string;
    uploadTime: string;
    isNew: boolean;
}

const App: React.FC = () => {
    // 应用状态
    const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
    const [loadingModalVisible, setLoadingModalVisible] = useState<boolean>(false);
    const [authModalVisible, setAuthModalVisible] = useState<boolean>(false);
    const [syncProgress, setSyncProgress] = useState<number>(0);
    const [currentCategory, setCurrentCategory] = useState<string>('tech');
    const [searchTerm, setSearchTerm] = useState<string>('');
    const [timeFilter, setTimeFilter] = useState<string>('all');
    const [durationFilter, setDurationFilter] = useState<string>('all');
    const [sortFilter, setSortFilter] = useState<string>('newest');
    const [toolbarTitle, setToolbarTitle] = useState<string>('科技类视频 (23个频道)');
    const [updateTime, setUpdateTime] = useState<string>('10分钟前更新');
    const [categories, setCategories] = useState<Category[]>([]);
    const [channels, setChannels] = useState<Channel[]>([]); // New state for channels
    const [videos, setVideos] = useState<Video[]>([]); // New state for videos
    const [filteredVideos, setFilteredVideos] = useState<Video[]>([]); // Corrected declaration

    useEffect(() => {
        checkAuthStatus();
        handleOAuthCallback();
    }, []); // Run once on mount

    useEffect(() => {
        if (isAuthenticated) {
            fetchCategories();
        }
    }, [isAuthenticated]);

    useEffect(() => {
        if (isAuthenticated && currentCategory) {
            fetchChannelsAndVideosForCategory();
        }
    }, [isAuthenticated, currentCategory, categories]); // Add categories to dependency array

    useEffect(() => {
        // Call filterVideos as a pure function and update state
        const newFilteredVideos = filterVideosPure(videos, searchTerm, timeFilter, durationFilter, sortFilter);
        setFilteredVideos(newFilteredVideos);
        updateContent();
    }, [currentCategory, searchTerm, timeFilter, durationFilter, sortFilter, categories, videos]);

    // 检查授权状态
    const checkAuthStatus = () => {
        const accessToken = localStorage.getItem('access_token');
        const refreshToken = localStorage.getItem('refresh_token');
        setIsAuthenticated(!!accessToken && !!refreshToken);
    };

    // 处理OAuth回调
    const handleOAuthCallback = async () => {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        const state = urlParams.get('state');

        if (code && state) {
            setLoadingModalVisible(true);
            try {
                const response = await fetch(`${API_BASE_URL}/auth/callback?code=${code}&state=${state}`);
                const data = await response.json();

                if (response.ok) {
                    localStorage.setItem('access_token', data.access_token);
                    localStorage.setItem('refresh_token', data.refresh_token);
                    setIsAuthenticated(true);
                    showSuccessMessage();
                } else {
                    alert(`认证失败: ${data.detail || '未知错误'}`);
                    setIsAuthenticated(false);
                }
            } catch (error) {
                console.error('OAuth回调处理失败:', error);
                alert('认证过程中发生错误，请重试。');
                setIsAuthenticated(false);
            } finally {
                setLoadingModalVisible(false);
                // 清除URL中的code和state参数
                window.history.replaceState({}, document.title, window.location.pathname);
            }
        }
    };

    // 显示需要授权的状态
    const showAuthRequired = () => {
        setTimeout(() => {
            setAuthModalVisible(true);
        }, 1000);
    };

    // 开始授权流程
    const startAuth = async () => {
        setAuthModalVisible(false);
        try {
            const response = await fetch(`${API_BASE_URL}/auth/login`);
            const data = await response.json();

            if (response.ok) {
                window.location.href = data.authorization_url; // 重定向到Google授权页面
            } else {
                alert(`获取授权URL失败: ${data.detail || '未知错误'}`);
            }
        } catch (error) {
            console.error('获取授权URL失败:', error);
            alert('无法开始认证流程，请检查网络或稍后重试。');
        }
    };

    // 模拟授权过程 (此函数在真实API集成后将不再需要)
    const simulateAuthProcess = () => {
        let progress = 0;
        const interval = setInterval(() => {
            progress += Math.random() * 15;
            if (progress >= 100) {
                progress = 100;
                clearInterval(interval);
                setTimeout(completeAuth, 500);
            }
            setSyncProgress(Math.floor(progress));
        }, 300);
    };

    // 完成授权 (此函数在真实API集成后将不再需要)
    const completeAuth = () => {
        localStorage.setItem('youtube_auth_token', 'mock_token_' + Date.now());
        setIsAuthenticated(true);
        setLoadingModalVisible(false);
        showSuccessMessage();
        fetchCategories(); // Fetch categories after successful authentication
    };

    // 显示成功消息
    const showSuccessMessage = () => {
        const message = document.createElement('div');
        message.innerHTML = `
            <div style="position: fixed; top: 20px; right: 20px; background: #10b981; color: white; 
                       padding: 15px 20px; border-radius: 8px; z-index: 1001; box-shadow: 0 4px 16px rgba(0,0,0,0.2);">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span>✅</span>
                    <span>授权成功！已同步100个订阅频道</span>
                </div>
            </div>
        `;
        document.body.appendChild(message);

        setTimeout(() => {
            message.remove();
        }, 3000);
    };

    // 登出功能
    const logout = async () => {
        if (window.confirm('确定要断开YouTube账户连接吗？')) {
            try {
                const accessToken = localStorage.getItem('access_token');
                const response = await fetch(`${API_BASE_URL}/auth/logout`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${accessToken}`,
                        'Content-Type': 'application/json',
                    },
                });

                if (response.ok) {
                    localStorage.removeItem('access_token');
                    localStorage.removeItem('refresh_token');
                    setIsAuthenticated(false);
                    window.location.reload();
                } else {
                    const data = await response.json();
                    alert(`登出失败: ${data.detail || '未知错误'}`);
                }
            } catch (error) {
                console.error('登出失败:', error);
                alert('登出过程中发生错误，请重试。');
            }
        }
    };

    // 获取分类数据
    const fetchCategories = async () => {
        const accessToken = localStorage.getItem('access_token');
        if (!accessToken) {
            console.warn('未找到访问令牌，无法获取分类。');
            return;
        }

        try {
            const response = await fetch(`${API_BASE_URL}/categories`, {
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                },
            });
            const data = await response.json();

            if (response.ok) {
                setCategories(data);
                // 默认选中第一个分类，如果没有则选中“未分类”
                if (data.length > 0) {
                    setCurrentCategory(data[0].name);
                } else {
                    setCurrentCategory('未分类'); // Fallback if no categories
                }
            } else {
                console.error('获取分类失败:', data.detail || '未知错误');
                alert(`获取分类失败: ${data.detail || '未知错误'}`);
            }
        } catch (error) {
            console.error('获取分类过程中发生错误:', error);
            alert('无法获取分类，请检查网络或稍后重试。');
        }
    };

    // 获取分类下的频道和视频
    const fetchChannelsAndVideosForCategory = async () => {
        const accessToken = localStorage.getItem('access_token');
        if (!accessToken) {
            console.warn('未找到访问令牌，无法获取频道和视频。');
            return;
        }

        const selectedCategory = categories.find(cat => cat.name === currentCategory);
        if (!selectedCategory) {
            setChannels([]);
            setVideos([]);
            return;
        }

        try {
            // Fetch channels for the selected category
            const channelsResponse = await fetch(`${API_BASE_URL}/categories/${selectedCategory.id}/channels`, {
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                },
            });
            const channelsData = await channelsResponse.json();

            if (channelsResponse.ok) {
                setChannels(channelsData.channels); // Assuming channelsData has a 'channels' key

                // Simulate fetching videos for these channels
                // In a real scenario, you would call a backend API that aggregates videos from these channels
                const fetchedVideos: Video[] = [];
                channelsData.channels.forEach((channel: Channel) => {
                    // This is a placeholder for actual video fetching logic
                    // For now, we'll just create some dummy videos based on channel info
                    for (let i = 0; i < 3; i++) { // Simulate 3 videos per channel
                        fetchedVideos.push({
                            title: `${channel.title} - Video ${i + 1}`,
                            channel: channel.title,
                            duration: `0${Math.floor(Math.random() * 10)}:00`,
                            views: `${Math.floor(Math.random() * 100)}万`,
                            uploadTime: `${Math.floor(Math.random() * 7) + 1}天前`,
                            isNew: Math.random() > 0.5,
                        });
                    }
                });
                setVideos(fetchedVideos);

            } else {
                console.error('获取频道失败:', channelsData.detail || '未知错误');
                alert(`获取频道失败: ${channelsData.detail || '未知错误'}`);
                setChannels([]);
                setVideos([]);
            }
        } catch (error) {
            console.error('获取频道和视频过程中发生错误:', error);
            alert('无法获取频道和视频，请检查网络或稍后重试。');
            setChannels([]);
            setVideos([]);
        }
    };

    // 筛选视频 (纯函数)
    const filterVideosPure = (
        allVideos: Video[],
        currentSearchTerm: string,
        currentTimeFilter: string,
        currentDurationFilter: string,
        currentSortFilter: string
    ): Video[] => {
        let filtered = [...allVideos];

        // 应用搜索筛选
        if (currentSearchTerm) {
            filtered = filtered.filter(video =>
                video.title.toLowerCase().includes(currentSearchTerm) ||
                video.channel.toLowerCase().includes(currentSearchTerm)
            );
        }

        // 应用时间筛选
        if (currentTimeFilter !== 'all') {
            filtered = filtered.filter(video => {
                if (currentTimeFilter === 'today') return video.uploadTime.includes('小时前');
                if (currentTimeFilter === 'week') return video.uploadTime.includes('天前') && parseInt(video.uploadTime) <= 7;
                if (currentTimeFilter === 'month') return video.uploadTime.includes('天前') && parseInt(video.uploadTime) <= 30;
                return true;
            });
        }

        // 应用时长筛选
        if (currentDurationFilter !== 'all') {
            filtered = filtered.filter(video => {
                const duration = video.duration.split(':');
                const minutes = parseInt(duration[0]) + parseInt(duration[1]) / 60;
                if (currentDurationFilter === 'short') return minutes < 4;
                if (currentDurationFilter === 'medium') return minutes >= 4 && minutes <= 20;
                if (currentDurationFilter === 'long') return minutes > 20;
                return true;
            });
        }

        // 应用排序
        if (currentSortFilter === 'popular') {
            filtered.sort((a, b) => {
                const aViews = parseInt(a.views.replace(/[万,]/g, ''));
                const bViews = parseInt(b.views.replace(/[万,]/g, ''));
                return bViews - aViews;
            });
        } else if (currentSortFilter === 'channel') {
            filtered.sort((a, b) => a.channel.localeCompare(b.channel, 'zh-CN'));
        }

        return filtered;
    };

    // 更新内容 (基于状态)
    const updateContent = () => {
        const selectedCategory = categories.find(cat => cat.name === currentCategory);
        const categoryDisplayName = selectedCategory ? `${selectedCategory.icon || ''} ${selectedCategory.name}`.trim() : currentCategory;
        const channelCount = channels.length; // Use actual channels count
        setToolbarTitle(`${categoryDisplayName}视频 (${channelCount}个频道)`);
    };

    // 添加分类
    const addCategory = async (categoryName: string) => {
        const accessToken = localStorage.getItem('access_token');
        if (!accessToken) {
            alert('请先登录以添加分类。');
            return;
        }

        try {
            const response = await fetch(`${API_BASE_URL}/categories`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ name: categoryName, description: '', icon: '', color: '' }),
            });
            const data = await response.json();

            if (response.ok) {
                alert(`分类 "${categoryName}" 添加成功！`);
                fetchCategories(); // Refresh categories after adding
            } else {
                alert(`添加分类失败: ${data.detail || '未知错误'}`);
            }
        } catch (error) {
            console.error('添加分类过程中发生错误:', error);
            alert('无法添加分类，请检查网络或稍后重试。');
        }
    };

    // 打开频道管理器
    const openChannelManager = () => {
        alert('打开频道分类管理界面');
    };

    // 刷新内容
    const refreshContent = () => {
        alert('正在刷新内容...');
        setUpdateTime('刚刚更新');
        fetchCategories(); // Refresh categories on content refresh
        if (isAuthenticated && currentCategory) {
            fetchChannelsAndVideosForCategory(); // Also refresh channels and videos
        }
    };

    // 打开视频
    const openVideo = (video: any) => {
        alert(`打开视频: ${video.title}`);
    };

    return (
        <div className="container">
            <Header isAuthenticated={isAuthenticated} onConnectClick={startAuth} />

            <div className="main-content" style={{ opacity: isAuthenticated ? '1' : '0.3', pointerEvents: isAuthenticated ? 'auto' : 'none' }}>
                <Sidebar
                    currentCategory={currentCategory}
                    onCategoryChange={setCurrentCategory}
                    onAddCategory={addCategory}
                    onOpenChannelManager={openChannelManager}
                    categories={categories} // Pass categories to Sidebar
                />

                <ContentArea
                    currentCategory={currentCategory}
                    filteredVideos={filteredVideos}
                    onRefreshContent={refreshContent}
                    onLogout={logout}
                    onOpenVideo={openVideo}
                    onSearchChange={(e) => setSearchTerm(e.target.value)}
                    onTimeFilterChange={(e) => setTimeFilter(e.target.value)}
                    onDurationFilterChange={(e) => setDurationFilter(e.target.value)}
                    onSortFilterChange={(e) => setSortFilter(e.target.value)}
                    toolbarTitle={toolbarTitle}
                    updateTime={updateTime}
                />
            </div>

            <AuthModal isVisible={authModalVisible} onStartAuth={startAuth} />
            <LoadingModal isVisible={loadingModalVisible} progress={syncProgress} />
        </div>
    );
};

export default App;
